<?php

namespace Wap\Controller;

use User\Model\NiudanModel;
use Wap\Service\WeixinService;

class NiudanController extends WapController
{
    public $wxuser;
    public $niudan;

    public function __construct()
    {
        parent::__construct();
        $this->_handleWx();
    }

    private function _handleWx()
    {
        $id = (I("get.id", -1, "") != -1) ? I("get.id", -1, "") : I("post.id", -1, "");
        if($id != -1){
            $this->niudan = M("redpacket")->where(['id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])->find();
            if(!empty($this->niudan)){
                $this->wxuser = WeixinService::getWxuser($this->niudan["token"]);
                if ($_SERVER['HTTP_HOST'] == "192.168.1.137") {         //本地
                    $openid = get_client_ip();
                    session('niudan_openid_'.$id, $openid);
                }
            }
        }
    }

    public function index()
    {
        $id = I("get.id", -1, "");
        $shock = I("get.shock", -1, "");
        $xcxid = I("get.xcxid", "", "");
        $code = I("get.code", "", "");
        if(S($shock) == 1){

        }else{
            S($shock, 0);
        }
        if(!empty($this->niudan)){
            $wxJSApi = WeixinService::buildWXJSApi($this->wxuser);
            $wxConfig = array(
                'appId' => $this->wxuser['appid'],
                'timestamp' => $wxJSApi['timestamp'],
                'nonceStr' => $wxJSApi['noncestr'],
                'signature' => $wxJSApi['sha1']
            );
            $wxShare = array(
                'share_title' => $this->niudan['share_title'] ? $this->niudan['share_title'] : $this->niudan['title'],
                'share_desc' => $this->niudan['share_desc'] ? $this->niudan['share_desc'] : $this->niudan['title'],
                'share_link' => $this->niudan['share_link'] ? $this->niudan['share_link'] :
                    "https://".$_SERVER['HTTP_HOST']."/Wap/Niudan/index?id=".$id,
                'share_image' => $this->niudan['share_img'] ? "https://".$_SERVER['HTTP_HOST'].$this->niudan['share_img'] :
                    "https://".$_SERVER['HTTP_HOST']."/Public/images/share_niudan.jpg"
            );
        }else{
            header("Content-type: text/html; charset=utf-8");
            die("活动不存在！");
        }
        if($xcxid != "" && $shock != -1){          //小程序访问
            session('niudan_openid_'.$id, $xcxid);
            session($xcxid.$id, 1);
            $this->_registerFans();
            $this->assign('title', $this->niudan["title"]);
            $this->assign('wxConfig', $wxConfig);
            $this->assign('wxShare', $wxShare);
            $this->display();
        }else{
            $openid = session("niudan_openid_".$id);
            if($openid){
                session($openid.$id, 2);
                $this->_registerFans();
                $this->assign('title', $this->niudan["title"]);
                $this->assign('wxConfig', $wxConfig);
                $this->assign('wxShare', $wxShare);
                $this->display();
            }else{
                if($code){
                    $id = I("get.id", -1, "");
                    $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                    $openid = $wechat->snsapiBaseUser($code);
                    session('niudan_openid_'.$id, $openid);
                    session($openid.$id, 2);
                    $this->_registerFans();
                    $this->assign('title', $this->niudan["title"]);
                    $this->assign('wxConfig', $wxConfig);
                    $this->assign('wxShare', $wxShare);
                    $this->display("index");
                }else{
                    $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
                    $url = $wechat->buildOauthURI("https://" . $_SERVER['HTTP_HOST'] . "/Wap/Niudan/index?id=".$id.
                        "&shock=".$shock);
                    redirect($url);
                }
            }
        }
    }

    private function _registerFans()
    {
        $id = $this->niudan["id"];
        $openid = session("niudan_openid_" . $id);
        $cond['pid'] = $id;
        $cond['openid'] = $openid;
        $cond['status'] = NiudanModel::FANS_ACTIVE;
        $fans = M("redpacket_fans")->where($cond)->find();
        if(empty($fans)){
            $data = array(
                'token' => $this->niudan['token'],
                'pid' => $this->niudan["id"],
                'openid' => $openid
            );
            M('redpacket_fans')->add($data);
        }
    }

    public function getDetail()
    {
        $id = I("get.id", -1, "");
        if($id == -1){
            $this->ajaxReturn(array("status" => -1, "errMsg" => "id missing"));
        }
        $niudan = M("redpacket")->where(['id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])->find();
        $niudan_upload = M("redpacket_upload")->where(['redpacket_id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])
            ->find();
        $openid = session("niudan_openid_".$id);

        $fans = M("redpacket_fans")->where(['pid' => $this->niudan["id"], 'openid' => $openid, 'status' =>
            NiudanModel::FANS_ACTIVE])->find();
        $reserve = json_decode($niudan["reserve"], true);
        $data = array(
            "game_status" => 0,
            "info" => $niudan["info"] ? $niudan["info"] : "",
            "address_required" => $reserve["address"],
            "follow" => $reserve["follow"],
            "follow_qrImage" => $reserve["follow_qrImage"] ? "https://".$_SERVER['HTTP_HOST'].$reserve["follow_qrImage"]
                : "",
            "follow_status" => 1,
            "button_again" => $niudan_upload["image2"] ? "https://".$_SERVER['HTTP_HOST'].$niudan_upload["image2"] : "",
            "button_share" => $niudan_upload["image1"] ? "https://".$_SERVER['HTTP_HOST'].$niudan_upload["image1"] : "",
            "custom_type" => $niudan_upload['bgm'] ? $niudan_upload['bgm'] : NiudanModel::CUSTOM_TYPE1
        );
        $start_date = strtotime($niudan["startdate"]);
        $end_date = strtotime($niudan["enddate"]);
        if(time() < $start_date){
            $data["game_status"] = 0;   //还未开始
        }elseif(time() > $end_date){
            $data["game_status"] = 2;   //已结束
        }else{
            $data["game_status"] = 1;   //正在进行
        }
        if($fans["name"] != "" && $fans["phone"] != "" && $fans["reserve"] != ""){
            $data["contact_status"] = 1;
        }
        if($reserve["follow"] == 1){
            if($this->_followStatus($id)){
                $data["follow_status"] = 1;
            }else{
                $data["follow_status"] = 0;
            }
        }
        if($niudan_upload['bgm'] == NiudanModel::CUSTOM_TYPE1){
            $data["button_follow"] = "";
            $data["button_link"] = "";
        }elseif($niudan_upload['bgm'] == NiudanModel::CUSTOM_TYPE2){
            $data["button_follow"] = $niudan_upload["image3"] ? "https://".$_SERVER['HTTP_HOST'].
                $niudan_upload["image3"] : "";
            $data["button_link"] = $niudan_upload["audio1"];
        }else{
            $data["button_follow"] = $niudan_upload["audio2"] ? "https://".$_SERVER['HTTP_HOST'].
                $niudan_upload["audio2"] : "";
            $data["button_link"] = "";
        }
        $this->ajaxReturn(array("status" => 1, "detail" => $data));
    }

    public function getAward()
    {
        $id = I("get.id", -1, "");
        if($id == -1){
            $this->ajaxReturn(array("status" => -1, "errMsg" => "id missing"));
        }
        $openid = session('niudan_openid_'.$id);
        $where['pid'] = $id;
        $where['openid'] = $openid;
        $where['zhongjiang'] = NiudanModel::ZHONGJIANG_YES;
        $where['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
        $fansaward = M("redpacket_fansaward")->where($where)->order('createdate desc')->select();
        $data = $prize = $prizes = array();
        if (!empty($fansaward)) {
            foreach ($fansaward as $value) {
                $prize[] = $value['award_id'];
            }
            $items_where['id'] = array('IN', $prize);
            $items_where['status'] = NiudanModel::PRIZE_ACTIVE;
            $items = M('redpacket_item')->where($items_where)->select();
            foreach ($items as $item) {
                $prizes[$item['id']]['prize_name'] = $item['name'];
                $prizes[$item['id']]['prize_pic'] = "https://".$_SERVER['HTTP_HOST'].$item['pic'];
            }
            foreach ($fansaward as $value) {
                $data[] = array(
                    'award_time' => date("Y-m-d", strtotime($value['createdate'])),
                    'award_name' => $prizes[$value['award_id']]['prize_name'],
                    'award_pic' => $prizes[$value['award_id']]['prize_pic'],
                    'award_status' => ($value['status'] == NiudanModel::AWARD_CHECK) ? 1 : 0
                );
            }
        }
        $this->ajaxReturn(array("status" => 1, "data" => $data));
    }

    public function postInfo()
    {
        $id = I("post.id", -1, "");
        $name = I("post.name", "", "");
        $phone = I("post.phone", "", "");
        $address = I("post.address", "", "");
        if($id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'id missing'));
        }
        if(!$name || $name == ""){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'name missing'));
        }
        if(!$phone || $phone == ""){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'phone missing'));
        }
        $openid = session('niudan_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
        }
        $this->niudan = M('redpacket')->where(['id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])->find();
        $this->_registerFans();
        $where_fans['pid'] = $id;
        $where_fans['openid'] = $openid;
        $data = array('name' => $name, 'phone' => $phone, 'address' => $address);
        M('redpacket_fans')->where($where_fans)->save($data);
        $this->ajaxReturn(array('status' => 1));
    }

    public function getNiudan()
    {
        $id = I("get.id", -1, "");
        $shock = I("get.shock", -1, "");
        S($shock, 1);
        if($id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'id missing'));
        }
        $openid = session('niudan_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
        }
        $niudan = $this->niudan = M('redpacket')->where(['id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])->find();
        if(!empty($niudan)){
            $niudan_items = M('redpacket_item')->where(['redpacket_id' => $id, 'status' =>
                NiudanModel::PRIZE_ACTIVE])->select();
            if(!empty($niudan_items)){
                //是否在抽奖时间内
                $start_time = strtotime($niudan['startdate']);
                $end_time = strtotime($niudan['enddate']);
                $now_time = time();
                if ( ($now_time < $start_time) || ($now_time > $end_time) ) {
                    $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid time'));
                }
                $zhongjiang = false;
                $zhongjiang_id = 0;
                $zhongjiang_name = "";
                $valid_start = date("Y-m-d") . " 00:00:00";
                $valid_end = date("Y-m-d") . " 23:59:59";
                //每日中奖次数上限
                $where_total_limits["pid"] = $id;
                $where_total_limits['createdate'] = array("between", array($valid_start, $valid_end));
                $where_total_limits["zhongjiang"] = array("EQ", NiudanModel::ZHONGJIANG_YES);
                $where_total_limits["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
                $total_limits = M('redpacket_fansaward')->where($where_total_limits)->count();
                if($niudan["number_limits"] != -1 && $total_limits >= $niudan["number_limits"]){
                    return $this->_setAward($zhongjiang, $zhongjiang_id, $zhongjiang_name);
                }

                //每人中奖次数
                $where_total_fans["pid"] = $id;
                $where_total_fans["openid"] = $openid;
                $where_total_fans["zhongjiang"] = array("EQ", NiudanModel::ZHONGJIANG_YES);
                $where_total_fans["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
                $total_fans = M('redpacket_fansaward')->where($where_total_fans)->count();
                if($niudan["per_num_sum"] != -1 && $total_fans >= $niudan["per_num_sum"]){
                    return $this->_setAward($zhongjiang, $zhongjiang_id, $zhongjiang_name);
                }

                //每人每日游戏次数上限（包括分享次数）
                $where_share["openid"] = $openid;
                $where_share["url"] = 'https://'.$_SERVER['HTTP_HOST'].'/Wap/Niudan/index?id='.$id;
                $wechat_share = M("wechat_share")->where($where_share)->find();
                $extra_times = 0;
                if(!empty($wechat_share)){
                    $extra_times = $niudan["share_play"];
                }
                $where_fans_per_num["pid"] = $id;
                $where_fans_per_num["openid"] = $openid;
                $where_fans_per_num['createdate'] = array("between", array($valid_start, $valid_end));
                $where_fans_per_num["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
                $fans_per_num = M('redpacket_fansaward')->where($where_fans_per_num)->count();
                if( ($niudan["per_num"] != -1) && ($fans_per_num >= ($niudan["per_num"] + $extra_times)) ){
                    return $this->_setAward($zhongjiang, $zhongjiang_id, $zhongjiang_name);
                }

                foreach ($niudan_items as $item) {
                    if ($item['reserve'] <= 0) {
                        continue;
                    }
                    $range = $item['reserve'] * 100000;
                    $random = rand(1, 10000000);
                    if ($random <= $range) {
                        //奖品总数
                        $where_prize_total['pid'] = $niudan['id'];
                        $where_prize_total['award_id'] = $item['id'];
                        $where_prize_total['zhongjiang'] = array("EQ", NiudanModel::ZHONGJIANG_YES);
                        $where_prize_total['status'] = array("NEQ", NiudanModel::AWARD_DELETE);
                        $item_award = M("redpacket_fansaward")->where($where_prize_total)->count();
                        if ($item_award >= $item['number']) {
                            continue;
                        }else{
                            $zhongjiang = true;
                            $zhongjiang_id = $item["id"];
                            $zhongjiang_name = $item["name"];
                        }
                        break;
                    }
                }
                return $this->_setAward($zhongjiang, $zhongjiang_id, $zhongjiang_name);
            }else{
                $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid id'));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid id'));
        }
    }

    private function _setAward($zhongjiang, $zhongjiang_id, $zhongjiang_name)
    {
        $openid = session('niudan_openid_'.$this->niudan["id"]);
        $redpacket_fansaward = M("redpacket_fansaward");
        $valid_start = date("Y-m-d") . " 00:00:00";
        $valid_end = date("Y-m-d") . " 23:59:59";

        //每人每日游戏次数上限，返回剩余chance
        $where_share["openid"] = $openid;
        $where_share["url"] = 'https://'.$_SERVER['HTTP_HOST'].'/Wap/Niudan/index?id='.$this->niudan["id"];
        $wechat_share = M("wechat_share")->where($where_share)->find();
        $extra_times = 0;
        if(!empty($wechat_share)){
            $extra_times = $this->niudan["share_play"];
        }
        $where_fans_per_num["pid"] = $this->niudan["id"];
        $where_fans_per_num["openid"] = $openid;
        $where_fans_per_num['createdate'] = array("between", array($valid_start, $valid_end));
        $where_fans_per_num["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
        if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
            $fans_per_num = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                ->where($where_fans_per_num)->count();
        } else {
            $fans_per_num = M("redpacket_fansaward")->where($where_fans_per_num)->count();
        }
        if($this->niudan["per_num"] != -1){
            $chance = $this->niudan["per_num"] + $extra_times - $fans_per_num - 1;
            if($chance <= 0){
                $chance = 0;
            }
        }else{
            $chance = -1;
        }

        if($zhongjiang){
            $redpacket_fansaward->startTrans();
            $data = array(
                'token' => $this->niudan["token"],
                'pid' => $this->niudan["id"],
                'openid' => $openid,
                'award_id' => $zhongjiang_id,
                'zhongjiang' => NiudanModel::ZHONGJIANG_YES
            );
            $reserve["area"] = $this->_getIpInfo();
            $reserve["phoneType"] = $this->_phoneType();
            $reserve["origin"] = session($openid.$this->niudan["id"]) == 1 ? "小程序" : "微信";
            $data["reserve"] = json_encode($reserve);
            $redpacket_fansaward->add($data);

            //每日中奖次数上限
            $where_total_limits["pid"] = $this->niudan["id"];
            $where_total_limits['createdate'] = array("between", array($valid_start, $valid_end));
            $where_total_limits["zhongjiang"] = array("EQ", NiudanModel::ZHONGJIANG_YES);
            $where_total_limits["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
            if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                $total_limits = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_total_limits)->count();
            } else {
                $total_limits = M("redpacket_fansaward")->where($where_total_limits)->count();
            }
            if($this->niudan["number_limits"] != -1 && $total_limits > $this->niudan["number_limits"]){
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array('status' => 0, 'chance' => $chance));
            }

            //每人中奖次数
            $where_total_fans["pid"] = $this->niudan["id"];
            $where_total_fans["openid"] = $openid;
            $where_total_fans["zhongjiang"] = array("EQ", NiudanModel::ZHONGJIANG_YES);
            $where_total_fans["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
            if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                $total_fans = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                    ->where($where_total_fans)->count();
            } else {
                $total_fans = M("redpacket_fansaward")->where($where_total_fans)->count();
            }
            if($this->niudan["per_num_sum"] != -1 && $total_fans > $this->niudan["per_num_sum"]){
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array('status' => 0, 'chance' => $chance));
            }

            //每人每日游戏次数上限
            if( $this->niudan["per_num"] != -1 && ($fans_per_num > ($this->niudan["per_num"] + $extra_times)) ){
                $redpacket_fansaward->rollback();
                $this->ajaxReturn(array('status' => 0, 'chance' => $chance));
            }
            $redpacket_fansaward->commit();

            $this->ajaxReturn(array('status' => 1, 'chance' => $chance, 'win' => $zhongjiang_name));
        }else{
            $data = array(
                'token' => $this->niudan["token"],
                'pid' => $this->niudan["id"],
                'openid' => $openid,
                'zhongjiang' => NiudanModel::ZHONGJIANG_NO
            );
            $reserve["area"] = $this->_getIpInfo();
            $reserve["phoneType"] = $this->_phoneType();
            $reserve["origin"] = session($openid.$this->niudan["id"]) == 1 ? "小程序" : "微信";
            $data["reserve"] = json_encode($reserve);
            $redpacket_fansaward->add($data);
            $this->ajaxReturn(array('status' => 0, 'chance' => $chance));
        }
    }

    public function gameChance()
    {
        $id = I("get.id", -1, "");
        if($id == -1){
            $this->ajaxReturn(array('status' => -1, 'errMsg' => 'id missing'));
        }
        $openid = session('niudan_openid_'.$id);
        if(!$openid){
            $this->ajaxReturn(array('status' => -3, 'errMsg' => 'openid missing'));
        }
        $niudan = M('redpacket')->where(['id' => $id, 'status' => NiudanModel::STATUS_ACTIVE])->find();
        if(!empty($niudan)){
            $data = array(
                'token' => $niudan["token"],
                'openid' => $openid,
                'url' => 'https://'.$_SERVER['HTTP_HOST'].'/Wap/Niudan/index?id='.$id
            );
            $added = M("wechat_share")->add($data);

            if($added !== false){
                //剩余chance
                $extra_times = $niudan["share_play"];
                $valid_start = date("Y-m-d") . " 00:00:00";
                $valid_end = date("Y-m-d") . " 23:59:59";
                $where_fans_per_num["pid"] = $id;
                $where_fans_per_num["openid"] = $openid;
                $where_fans_per_num['createdate'] = array("between", array($valid_start, $valid_end));
                $where_fans_per_num["status"] = array("NEQ", NiudanModel::AWARD_DELETE);
                if ($_SERVER['HTTP_HOST'] == 'esm.zbxinmeiti.com') {
                    $fans_per_num = M("redpacket_fansaward", 'esm_', 'mysql://yunwei_test:j9IrRtVtqcxEM@rm-bp145cj7u5r5k813u.mysql.rds.aliyuncs.com:3306/esm#utf8')
                        ->where($where_fans_per_num)->count();
                } else {
                    $fans_per_num = M("redpacket_fansaward")->where($where_fans_per_num)->count();
                }
                if($niudan["per_num"] != -1){
                    $chance = $niudan["per_num"] + $extra_times - $fans_per_num;
                    if($chance <= 0){
                        $chance = 0;
                    }
                }else{
                    $chance = -1;
                }
                $this->ajaxReturn(array('status' => 1, 'chance' => $chance));
            }else{
                $this->ajaxReturn(array('status' => 0));
            }
        }else{
            $this->ajaxReturn(array('status' => -2, 'errMsg' => 'invalid id'));
        }
    }

    private function _followStatus($id)
    {
        $openid = session('niudan_openid_'.$id);
        if(empty($openid)){
            return false;
        }
        $token = $this->_getAccessToken();
        if(empty($token)){
            return false;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openid."&lang=zh_CN";
        $res = $this->curlGet($url);
        $res = json_decode($res, 1);
        if(isset($res['subscribe'])){
            if($res['subscribe'] == 1){
                return true;
            }else{
                return false;
            }
        }else{
            if(isset($res['errcode']) && $res['errcode'] == 40001){
                $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->wxuser['appid'] . "&secret=" .
                    $this->wxuser['appsecret'] . "&grant_type=client_credential";
                $res = $this->curlGet($url);
                $res = json_decode($res, 1);
                $token = isset($res['access_token']) ? $res['access_token'] : null;
                S( 'access_token_'.$this->wxuser['token'], $token, 6300 );
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $openid .
                    "&lang=zh_CN";
                $res = $this->curlGet($url);
                $res = json_decode($res, 1);
                if (isset($res['subscribe'])) {
                    if($res['subscribe'] == 1){
                        return true;
                    }else{
                        return false;
                    }
                } else {
                    return false;
                }
            }else if($res['errcode'] == 40003){
                $code = I("get.code", "", "");
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->wxuser['appid'] .
                    "&secret=" . $this->wxuser['appsecret'] . "&code=" . $code . "&grant_type=authorization_code";
                $exist = $this->curlGet($url);
                $exist = json_decode($exist, 1);
                $exist = isset($exist['openid']) ? $exist : null;
                session('niudan_openid_'.$id, $exist);
                $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $exist .
                    "&lang=zh_CN";
                $res = $this->curlGet($url);
                $res = json_decode($res, 1);
                if(isset($res['subscribe'])){
                    if($res['subscribe'] == 1){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    if (isset($res['errcode']) && $res['errcode'] == 40001) {
                        $url = "https://api.weixin.qq.com/cgi-bin/token?appid=" . $this->wxuser['appid'] . "&secret=" .
                            $this->wxuser['appsecret'] . "&grant_type=client_credential";
                        $res = $this->curlGet($url);
                        $res = json_decode($res, 1);
                        $token = isset($res['access_token']) ? $res['access_token'] : null;
                        S( 'access_token_'.$this->wxuser['token'], $token, 6300 );
                        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" .
                            $exist . "&lang=zh_CN";
                        $res = $this->curlGet($url);
                        $res = json_decode($res, 1);
                        if (isset($res['subscribe'])) {
                            if($res['subscribe'] == 1){
                                return true;
                            }else{
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }else{
                        return false;
                    }
                }
            }else{
                return false;
            }
        }
    }

    private function _getAccessToken()
    {
        $access_token = S( 'access_token_'.$this->wxuser['token'] );
        if( !$access_token ){
            $url_get = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' .
                $this->wxuser['appid'] . '&secret=' . $this->wxuser['appsecret'];
            $json = json_decode($this->curlGet($url_get));
            if (!$json -> errmsg){
                $access_token = $json -> access_token;
                S( 'access_token_'.$this->wxuser['token'], $access_token, 6300 );
            }else{
                $this->error('获取access_token发生错误：错误代码'.$json->errcode.',微信返回错误信息：'.$json->errmsg);
            }
        }
        return $access_token;
    }

    private function curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 500);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }

    private function _getIpInfo()       //淘宝接口,根据ip查询所在区域信息
    {
        $ip = get_client_ip();
//        $res = $this->curlGet("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
//        $res = json_decode($res,true);
        $area = '';
//        if($res['code'] == 0){
//            $area = $res['data']['city'];
//        }
        return $area;
    }

    private function _phoneType()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, "iPhone") !== false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false
            || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false
            || strpos($user_agent, "SM-") !== false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false
            || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo") !== false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false
            || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false
            || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false
            || strpos($user_agent, "5910") !== false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false
            || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false
            || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false
            || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false
            || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false
            || strpos($user_agent, "R2017") !== false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo") !== false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch") !== false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false
            || stripos($user_agent, "NX40") !== false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false
            || strpos($user_agent, "M355") !== false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV") !== false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE") !== false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia") !== false) {
            $brand = '诺基亚';
        } else {
            $brand = '其他手机';
        }
        return $brand;
    }

    public function niudanShock()
    {
        $shock = I("get.shock", -1, "");
        S($shock, 0);
        $this->ajaxReturn(array('status' => 1));
    }

    public function getNiudanShock()
    {
        $shock = I("get.shock", -1, "");
        $result = S($shock) ? S($shock) : 0;
        $this->ajaxReturn($result);
    }
    public function xcxGetopenid()
    {
        $code = I("get.code", '', '');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxe2303d6660660d54&secret=1fa9cc46b88e630961fbc9a1f6f16425&js_code='
            . $code . '&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $out = curl_exec($ch);
        curl_close($ch);
        $this->ajaxReturn($out);
    }
}